package com.spt.springbootzhsx.service;

import com.spt.springbootzhsx.entity.Movie;
import com.spt.springbootzhsx.entity.Rate;
import com.spt.springbootzhsx.mapper.MovieMapper;
import com.spt.springbootzhsx.mapper.RateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class RateImpl implements RateService {
    @Autowired
    private RateMapper rateMapper;
    @Autowired
    private MovieMapper movieMapper;


    @Override
    public String addRate(Rate rate) {
        ArrayList<Rate> list=rateMapper.getRateByUidAndMid(rate.getUid(),rate.getMid());
        if(list.size()>0){  //如果已经评分过
          return "评分失败！已经评论过！";
        }else{
            //插入评分记录
            rateMapper.addRate(rate);
            ArrayList<Rate> rates=rateMapper.getRateByMid(rate.getMid());
            Integer sum=0;
            for (Rate rate1 : rates) {
                sum+=rate1.getStar();
            }
            //计算电影新的评分
            Float ra = Float.valueOf(sum)/Float.valueOf(rates.size());
            //更新电影评分信息
            Movie movie=movieMapper.getMovieByMid(rate.getMid());
            movie.setRate(ra);
            int k=movieMapper.updateMovie(movie);
            if(k>=1){
                return "评分成功！";
            }else{
                return "评分失败！";
            }
        }
    }
}
